﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Joystick
{
    public Action<Vector2> OnMoveDrag;
    public Action OnMoveEnd;
    GameObject _root;
    RectTransform _innerBall;//内部小球
    RectTransform _outBall;//外部小球，摇杆激活区域

    float _radius = 0;
    Vector2 _centerPos;
    Vector2 _dir;

    public Joystick()
    {
         _root=UIMgr.GetInstance().Replace("UI/FightUI/Joystick",UILayer.FightUI);

        _outBall = _root.Find<RectTransform>("bg");
        _innerBall = _root.Find<RectTransform>("bg/inner");
        //小球的移动半径
        _radius = _outBall.rect.width * 0.5f;
        //大球的中心点
        _centerPos = new Vector2(0,0);

        var touchEx = _outBall.GetComponent<TouchEx>();

        touchEx.DragCallback += onDrag;
        touchEx.PointDownCallback += onPointDown;
        touchEx.PointUpCallback += onPointUp;
        TimerMgr.GetInstance().CreateTimerAndStart(0.1f,-1,OnLoop);
    }

    private void OnLoop()
    {
        if (_dir==Vector2.zero)
            return;
        if (OnMoveDrag != null)
            OnMoveDrag(_dir);
    }

    private void onPointUp(PointerEventData eventData)
    {
        Reset();
        if (OnMoveEnd != null)
            OnMoveEnd();
        

    }

    public void Reset()
    {
        _dir = Vector2.zero;
        _innerBall.localPosition = _centerPos;
    }

    private void onPointDown(PointerEventData eventData)
    {
        onDrag(eventData);
    }

    private void onDrag(PointerEventData eventData)
    {
      
        Vector2 targetpos;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(_outBall, eventData.position, eventData.pressEventCamera, out targetpos);
        var dir = targetpos - _centerPos;
        _dir = dir.normalized;

        _innerBall.GetComponent<RectTransform>().localPosition = _dir * Mathf.Min(dir.magnitude, _radius);

        //EventCenter.GetInstance().EventTrigger("OnMoveDir",_dir);
    }
}
